<?php
/**
 * 进销存系统对外提供的API接口信息
 * Created by PhpStorm.
 * User: z
 * Date: 14-8-22
 * Time: 下午2:38
 */
class Controller_Newerpapi extends Controller
{
    
    /**
     * 通用方法
     */
    public function action_query()
    {
        exit('此方法已禁用');
        require_once(Kohana::find_file('vendor','phprpc/phprpc_server'));
        $server = new PHPRPC_Server();
        function getData($type=Database::SELECT,$sql='')
        {
            if($sql)
            {
                 switch($type){
                     case Database::INSERT:
                         return DB::query(Database::INSERT,$sql)->execute('newerp');
                     case Database::UPDATE:
                         return DB::query(Database::UPDATE,$sql)->execute('newerp');
                     default:
                         return DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                 }
            }
        }
        $server->add('getData');
        $server->start();
    }

    /**
     * Wms订单执行扫描退件接口
     */
    public function action_doWmsReturnedParcel() {
        if(!isset($_POST['warehouseid']) || empty($_POST['warehouseid'])) {
            $re['code'] = 1000;
            $re['message'] = '仓库唯一ID标示warehouseid缺失';
            echo json_encode($re);
            exit;
        }

        if(!isset($_POST['deliveryorders_id']) || empty($_POST['deliveryorders_id'])) {
            $re['code'] = 1001;
            $re['message'] = '出库单ID缺失';
            echo json_encode($re);
            exit;
        }

        if(!isset($_POST['sku']) || empty($_POST['sku'])) {
            $re['code'] = 1002;
            $re['message'] = 'SKU缺失';
            echo json_encode($re);
            exit;
        }

        if(!isset($_POST['sku_name']) || empty($_POST['sku_name'])) {
            $re['code'] = 1003;
            $re['message'] = 'SKU中文名称缺失';
            echo json_encode($re);
            exit;
        }

        if(!isset($_POST['storage_position']) || empty($_POST['storage_position'])) {
            $re['code'] = 1004;
            $re['message'] = '储位缺失';
            echo json_encode($re);
            exit;
        }

        if(!isset($_POST['warehouse_quantity']) || empty($_POST['warehouse_quantity'])) {
            $re['code'] = 1005;
            $re['message'] = '入库数量缺失';
            echo json_encode($re);
            exit;
        }

        if(!isset($_POST['warehouse_man']) || empty($_POST['warehouse_man'])) {
            $re['code'] = 1008;
            $re['message'] = '入库人name缺失';
            echo json_encode($re);
            exit;
        }

        $userId = DB::select('id')->from('users')
            ->where('name','=',$_POST['warehouse_man'])
            ->limit(1)
            ->execute()
            ->get('id',0);

        if(!isset($_POST['type']) || empty($_POST['type'])) {
            $re['code'] = 1009;
            $re['message'] = '入库类型缺失';
            echo json_encode($re);
            exit;
        }

        $skuPriceArr = hznewerpclient::getNewPrice(array($_POST['sku']));
        $price = $skuPriceArr[$_POST['sku']];

        $options['warehouseid'] = $_POST['warehouseid'];
        $options['warehouse_date'] = $options['op_time'] = date('Y-m-d H:i:s');
        $options['purchaseorders_id'] = 0;
        $options['batch_code'] = 0;
        $options['returned_parcel_id'] = 0;
        $options['supplier_id'] = 0;
        $options['sku_standard'] = '';
        $options['tax_price'] = 0;
        $options['remark'] = '未出仓库前的包裹扫描回库，订单号是' . $_POST['remark'];
        $options['status'] = 0;
        $options['type'] = $_POST['type'];
        $options['warehouse_man'] = $userId;
        $options['store'] = 0;
        $options['export_tax_rebate'] = 0;
        $options['enterprise_dominant'] = 1;
        $options['transfer_hopper_id'] = 0;
        $options['transfer_type'] = 0;

        $options['cost'] = $price * $_POST['warehouse_quantity'];
        $options['single_price'] = $price;
        $options['money'] = $price * $_POST['warehouse_quantity'];

        $re['code'] = 0;
        $re['message'] = 'Connect OK';
        $re['data'] = DB::insert('warehouseorders')->columns(array_keys($options))->values($options)->execute('newerp');

        echo json_encode($re);
        exit;
    }
    
    /**
     * 描述:判断是否vmi系统可用sku
     * 参数:$_GET['sku']或$_POST['sku']=array('A301','A302')
     * 作者:kelvin
     */
    public function action_checkSkuInVmi()
    {
        $skus = empty($_POST['sku']) ? $_GET['sku']: $_POST['sku'];
        $result = newerpapi::checkSkuInVmi($skus);
        echo json_encode($result);
        exit;
    }

    /**
     * 描述:判断SKU是否有库存
     * 参数:$_POST['data']
     */
    public static function action_checkSkuInventoryInVMI() {
        $deliveryData = json_decode($_POST['data'], true);
        $checkSKUInventory = newerpapi::checkSkuInventoryInVmi($deliveryData);

        echo json_encode($checkSKUInventory);
        exit;
    }

    /**
     * 描述：获取出库数据
     * 参数：出库开始时间、出库结束时间
     */
    public function action_getDeliveryInfo() {
        $re = array();

        if (empty($_POST)) {
            $re['status'] = 500;
            $re['msg'] = "参数为空！";
            $re['data'] = array();
        } else {
            $col = array('d.id', 'd.supplier_id', 'd.sku', 'd.order_id', 'd.orders_products_id', 'd.delivery_date',
                'd.single_price', 'd.quantity');

            $dataObj = DB::select_array($col)
                ->from(array('deliveryorders', 'd'))
                ->where('d.type', '=', 10);
            isset($_POST['delivery_date_start']) && $dataObj->where('d.delivery_date', '>=', $_POST['delivery_date_start']);
            isset($_POST['delivery_date_end']) && $dataObj->where('d.delivery_date', '<=', $_POST['delivery_date_end']);

            $data = $dataObj->execute('newerp')->as_array();

            $re['status'] = 200;
            $re['msg'] = "请求成功";
            $re['data'] = $data;
        }

        echo json_encode($re);
        exit;
    }

    /**
     * 描述：扫描回库的新建入库单
     */
    public function action_returnWarehouse() {
        $user_id = User::active_user()->id;
        $insert_val = array();
        $result = array();

        if ($_POST['order_id']) {
            $sql = "SELECT * FROM `deliveryorders` WHERE `order_id`=" . $_POST['order_id'];
            $res = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
            if(!empty($res)){
                foreach($res as $re){
                    if($re['sku']=='' ||$re['quantity']==0){
                        continue;
                    }

                    $supplier = new Service_Common();
                    $price = $supplier->get_sku_price($re['sku']);
                    $wo = ORM::factory('warehouseorder');

                    $wo->warehouseid = $re['warehouseid'];
                    $wo->warehouse_date = date('Y-m-d H:i:s');
                    $wo->op_time = date('Y-m-d H:i:s');
                    $wo->deliveryorders_id = $re['id'];
                    $wo->sku = $re['sku'];
                    $wo->sku_name = $re['sku_name'];
                    $wo->sku_standard = $re['sku_standard'];
                    $wo->storage_position = $re['storage_position'];
                    $wo->warehouse_quantity= $re['quantity'];
                    if($re['single_price'] == 0) {
                        $wo->single_price = $price;
                        $wo->money = $price * $re['quantity'];
                    }else{
                        $wo->single_price = $re['single_price'];
                        $wo->money = $re['money'];
                    }
                    $wo->supplier_id = $re['supplier_id'];
                    $wo->cost = $price*$re['quantity'];
                    $wo->remark = '未出仓库前的包裹扫描回库，订单号是'.$re['order_id'];
                    $wo->type = 80;
                    $wo->warehouse_man = $user_id;
                    $insert_val[] = $wo->save();
                }
            }

            if (sizeof($res) != sizeof($insert_val)) {
                if (sizeof($insert_val) > 0) {
                    DB::delete('deliveryorders')->where('id', 'IN', $insert_val)->execute('newerp');
                }

                $result['msg'] = $_POST['order_id'] . '该订单号回库失败！数据插入不成功！';
                $result['status'] = 500;
            } else {
                $result['status'] = 200;
                $result['msg'] = "扫描回库成功";
            }
        } else {
            $result['status'] = 500;
            $result['msg'] = "参数缺失！";
        }


        echo json_encode($result);
        exit;
    }
    
    /**
     * 获取SKU实时库存（指定供应商）
     * 请求参数：$_POST['data'] = "{\"supplier_id\":123,\"skus\":[\"A301\",\"A302\"]}";供应商ID必须，skus可选
     * 响应结果：{"SKU":{"仓库ID":"库存数"}}，如：{"msg":"success","code":1,"data":{"AM521900":{"5":10}}}
     */
    public function action_getSkuStocks() {
        if(self::check_sign($_POST)==false){
            $this->ajaxReturn('签名验证失败');
        }
        $post = $_POST['data'];
        $query = json_decode($post, true);
        $supplier_id = isset($query['supplier_id']) ? (int)$query['supplier_id'] : 0;
        $warehouse_id = isset($query['warehouse_id']) ? (int)$query['warehouse_id'] : 0;
        $skus = isset($query['skus']) ? $query['skus'] : array();
        if(!is_array($skus)) {
            $skus = explode(',', $skus);
        }
        $skus = array_filter(array_map('addslashes', $skus));
        $supplier_id || $this->ajaxReturn('未指定有效的供应商ID');
        $condition = array('supplier_id' => $supplier_id);
        if(!empty($skus)) {
            $condition['sku'] = $skus;
        }
        $stocks = array();
        $results = Inventory::get_real_stocks($warehouse_id, $condition);
        if(!empty($results)) {
            foreach ($results as $row) {
                $stocks[$row['sku']][$row['warehouseid']] += $row['quantity'];
            }
        }
        if(!empty($skus)) {
            foreach($skus as $sku) {
                $stocks[$sku] = isset($stocks[$sku]) ? $stocks[$sku] : array();
            }
        }
        $this->ajaxReturn('success', $stocks);
    }
    
    // JSON格式输出结果
    protected function ajaxReturn($info, $data = false, $code = 1) {
        $result = array(
            'msg'   => $info,
            'code'  => intval($code),
        );
        if($data !== false) {
            $result['data'] = $data;
        }
        echo json_encode($result);
        exit;
    }
    
    /**
     *  验证签名 $key = md5('9610vmi');
     *  作者:kelvin
     * */
    public static function check_sign($data,$key='52275b50893f4d33bde2dfaa44144735')
    {
        if(md5($data['data'].$key)==$data['sign']){
            return true;
        }else{
            return false;
        }
    }
}
